
import { GetQueryString, JudgeQueryString } from 'clientConfig/util/queryurlfield';
import { getDomRouter } from 'clientConfig/util/Page_router';
const { Router, Route, IndexRoute, Link, hashHistory } = ReactRouter;
const DingClient = require('clientConfig/util/DingClient');
const Storage = require('clientConfig/util/StoreData').Storage;
const net = require('clientConfig/util/net');
const urllist = require('clientConfig/urllist');
let corpid = GetQueryString("corpid");
// Storage.set('user', {})
Storage.set('user.corpid', corpid)
let bpUserID = GetQueryString("bpUserID") || '';
let bpPassword = GetQueryString("bpPassword") || '';
let bpUserGUID = GetQueryString("bpUserGUID") || '';
let bpPortalID = GetQueryString("bpPortalID") || '';
let bpResourceName = GetQueryString("bpResourceName") || '';
// window.isBp = JudgeQueryString('bpUserID');//true内网，false外网(移至html中，防止关键db获取不到window.isBp)
let appid = GetQueryString("appid");
let apptype = GetQueryString("apptype");
let devtype = GetQueryString("devtype");
let start = Symbol('fnstart');
let bpStart = Symbol('bpStart');
let monStorage = require('./StoreData').monStorage
const { Toast } = SaltUI;
function bar(info) {
    this[start](info);
}
class Appjudge {
    /*
     *signUrl:签名的url
     *corpid：授权企业id
     *appid：授权应用id
     *apptype:应用类型0微应用1服务窗应用
     *devtype:1手机2pc
    */
    static init() {
        var t = this;
        let url = location.href.split('#', 1);
        let signUrl = encodeURIComponent(url);
        if (!window.isBp) {
            window.type = 'ding'
            if (apptype == 0 && devtype == 1) {
                //手机微应用
                var urlprefix = urllist.getjsapi;
            } else if (apptype == 0 && devtype == 2) {
                //pc微应用
                var urlprefix = urllist.getjsapi;
            } else if (apptype == 1 && devtype == 1) {
                //手机服务窗
                var urlprefix = urllist.getchanneljsapi;
            }
            if (corpid && appid) {
                //jsapi验证
                net.fetchUrl(urlprefix + "?corpid=" + corpid + '&appid=' + appid + '&url=' + signUrl).then((jsondata) => {
                    let agentId = jsondata.agentid;
                    
                    Storage.set('user.agentid', jsondata.agentid);
                    if (jsondata.url == url) {
                        /**获取免登码*/
                        DingClient.clientConfig(jsondata, apptype, devtype, function (isSuccessed, data) {
                            if (isSuccessed) {
                                //微应用
                                apptype == 0 && devtype == 1 && dd.runtime.permission.requestAuthCode({
                                    corpId: corpid,
                                    onSuccess: function (result) {
                                        //1.code获取微应用关注者信息
                                        t.loginmicro(result.code, corpid);
                                    },
                                    onFail: function (err) { }
                                });
                                apptype == 0 && devtype == 2 && DingTalkPC.runtime.permission.requestAuthCode({
                                    corpId: corpid, //企业ID
                                    onSuccess: function (result) {
                                        t.loginmicro(result.code, corpid);
                                    },
                                    onFail: function (err) { }

                                })
                                //服务窗
                                apptype == 1 && devtype == 1 && dd.channel.permission.requestAuthCode({
                                    corpId: corpid,
                                    onSuccess: function (result) {
                                        //1.免登获取openid 2.code获取服务窗关注者信息
                                        t.getopenid(jsondata.corpid, result.code).then((jsondata) => {
                                            t.loginservice(jsondata, corpid);
                                        });
                                    },
                                    onFail: function (err) { }
                                });
                            } else {
                                console.log(JSON.stringify(data));
                            }
                        });
                    } else {
                        console.log('签名的url不一致');
                    }
                });
            } else {

                Toast.show({
                    type: 'error',
                    content: '获取corpid失败，免登出错'
                });
            }
        } else {
            //业务基础平台直接进入绑定
            window.type = 'bp'
            let bpInfo = {
                bpUserID,
                bpPassword,
                bpUserGUID,
                bpPortalID,
                bpResourceName
            }
            monStorage.set('user.bpPassword', bpInfo.bpPassword)
            monStorage.set('user.bpPortalID', bpInfo.bpPortalID)
            monStorage.set('user.bpResourceName', bpInfo.bpResourceName)
            monStorage.set('user.nickname', bpInfo.bpUserID)
            Storage.set('user.unionid', bpInfo.bpUserGUID)
            Storage.set('user.nickname', bpInfo.bpUserID)
            getDomRouter();
            // t.loginBp(bpInfo, bpUserGUID);
        }
    }
    //微应用获取用户信息
    static loginmicro(code, corpid) {
        net.fetchUrl(urllist.getuserinfo + "?code=" + code + '&corpid=' + corpid).then((jsondata) => {
            if (jsondata.errcode == 0) {
                bar.call(this, jsondata);
            } else {
                console.log('获取用户信息失败');
                return;
            }
        });
    }
    //微应用获取用户信息
    static loginBp(body, unionid) {
        let url = urllist.getInfoById + '?type=' + window.type + '&id=' + unionid;
        net.fetchUrl(url, { method: 'post', body: { ...body } }).then((jsondata) => {
            if (jsondata.errcode == 0) {
                // bar.call(this, jsondata.user);
                getDomRouter();
            } else {
                console.log('获取用户信息失败');
                return;
            }
        });
    }
    //服务窗才有的流程
    getopenid(corpid, code) {
        //手机服务窗
        var urlprefix = urllist.getuserchannelcode;
        net.fetchUrl(urlprefix + "?corpid=" + corpid + '&code=' + code).then((jsondata) => {
            if (jsondata.errcode == 0) {
                Storage.set('user.unionid', jsondata.unionid);
                Storage.set('user.openid', jsondata.openid);
                return jsondata;
            }
        });
    }
    //服务窗获取用户信息
    loginservice(jsonresult, corpid) {
        let unionid = jsonresult.unionid;
        let openid = jsonresult.openid;
        net.fetchUrl(urllist.bindtel + "?unionid=" + unionid).then((jsondata) => {
            if (jsondata.errcode == 1) {
                telbindstate = false;//1为未绑定
                // alert("用户未绑定手机号");
            }
            telbindstate = false;
            // alert("openid=" + openid);
        });
        net.fetchUrl(urllist.getchanneluserinfo + "?openid=" + openid + '&corpid=' + corpid).then((jsondata) => {
            // alert('jsondata1=' + JSON.stringify(jsondata1));
            if (jsondata1.errcode == 0) {
                // alert('登录成功');
                jsondata1.nickname && Storage.set('user.nickname', jsondata1.nickname);
                jsondata1.avatar && Storage.set('user.avatar', jsondata1.avatar);
                Storage.set('user.subscribe', jsondata1.subscribe);
                jsapiJudge = true;
                let agentId = Storage.get('user.agentid');
                // this[start](agentId);
            }
        });
    }
    static [start](info) {
        // monStorage.set('user', {})
        monStorage.set('user.nickname', info.name)
        monStorage.set('user.mobile', info.mobile)
        monStorage.set('user.email', info.email)
        monStorage.set('user.position', info.position)
        monStorage.set('user.department', info.department)
        monStorage.set('user.avatar', info.avatar)
        monStorage.set('user.corp_name', info.corp_name)
        Storage.set('user.unionid', info.unionid)
        Storage.set('user.nickname', info.name)
        // console.log(JSON.stringify(info))
        // alert(JSON.stringify(info))
        getDomRouter();
        if (!window.isBp) dd.ui.webViewBounce.disable();
    }
}

module.exports = Appjudge;